<?php

define ('MODULE_NAME', 'clamav');
define ('SCRIPT_VERSION', 0.9);
define ('UPDATE_SERVER', 'extendplesk.com');
define ('WRAPPER','clamav');



class IndexController extends pm_Controller_Action
{
    public function init()
    {
        parent::init();

        // Init title for all actions
        $this->view->pageTitle = 'Clam AntiVirus';

        // Init tabs for all actions
        $this->view->tabs = array(
            array(
                'title' => 'Scheduler',
                'action' => 'form',
            ),
          //  array(
          //      'title' => 'Tools',
          //      'action' => 'tools',
          //  ),
            array(
                'title' => 'Scan Results',
                'action' => 'list',
            ),
        );
    }

    public function indexAction()
    {
        // Default action will be formAction
        $this->_forward('form');
    }

    public function formAction()
    {
        //For checking cron entries
        $pattern = '/^(?:[1-9]?\d|\*)(?:(?:[\/-][1-9]?\d)|(?:,[1-9]?\d)+)?$/';
        $cronExample ='
        If custom scheduling is selected please update the following settings.<br/>

    Setting     - Description<br/>
    30      – 30th Minute<br/>
    08      – 08 AM<br/>
    10      – 10th Day<br/>
    06      – 6th Month (June)<br/>
    *       – Every day of the week<br/>';
        // Display simple text in view
        // Just in case my server is down it does not crash extention
        $ctx = stream_context_create(array( 
            'http' => array( 
            'timeout' => 3 )));
        $UpdateCheck = file_get_contents("http://extendplesk.com/versioncheck.php?module=".MODULE_NAME."&version=".SCRIPT_VERSION, 0, $ctx);

        //$this->view->test = $UpdateCheck.'<br>';
        $this->view->test = '<br>';;


        // Init form here
        $form = new pm_Form_Simple();
        $form->addElement('simpleText', 'exampleSimpleText2', array(
            'label' => 'Version Check:',
            'escape' => false,
            'value' => $UpdateCheck,
        ));
        $form->addElement('text', 'emailText', array(
           'label' => 'Alert on Virus Email [optional]',
           'value' => pm_Settings::get('emailText'),
           'required' => false,
            'validators' => array(
             array('NotEmpty', true),
           ),
        ));

        $form->addElement('select', 'scheduleSelect', array(
            'label' => 'Select Scan Schedule',
            'multiOptions' => array('opt-0' => 'Never', 'opt-1' => 'Hourly','opt-2' => 'Daily','opt-3' => 'Weekly','opt-4' => 'Monthly', 'opt-5' => 'Custom'),
            'value' => pm_Settings::get('scheduleSelect'),
            'required' => true,
        ));
        $form->addElement('simpleText', 'exampleSimpleText3', array(
            'label' => 'Custom Schedule: ',
            'escape' => false,
            'value' => $cronExample,
        ));
        $form->addElement('text', 'cronMinute', array(
            'label' => 'Minute',
            'value' => pm_Settings::get('cronMinute'),
            'required' => false,
            'validators' => array(
             array('regex', false, array($pattern)),
           ),
        ));
        $form->addElement('text', 'cronHour', array(
            'label' => 'Hour',
            'value' => pm_Settings::get('cronHour'),
            'required' => false,
            'validators' => array(
             array('NotEmpty', true),
           ),
        ));
        $form->addElement('text', 'cronDOM', array(
            'label' => 'Day of the Month ',
            'value' => pm_Settings::get('cronDOM'),
            'required' => false,
            'validators' => array(
             array('NotEmpty', true),
           ),
        ));
        $form->addElement('text', 'cronMonth', array(
            'label' => 'Month',
            'value' => pm_Settings::get('cronMonth'),
            'required' => false,
            'validators' => array(
             array('NotEmpty', true),
           ),
        ));
        $form->addElement('text', 'cronDOW', array(
            'label' => 'Day of the Week',
            'value' => pm_Settings::get('cronDOW'),
            'required' => false,
            'validators' => array(
             array('NotEmpty', true),
           ),
        ));
        $form->addElement('simpleText', 'exampleSimpleText', array(
            'label' => 'Domains To Scan:',
			'escape' => false,
            'value' => '<hr>',
        ));


        pm_Bootstrap::init();
        $domainset = pm_Bootstrap::getDbAdapter()->query("select * from domains where htype='vrt_hst'");
        $iconPath = pm_Context::getBaseUrl() . 'images/icon_16.gif';
        while ($row = $domainset->fetch()) {
            $domainRoot = pm_Bootstrap::getDbAdapter()->fetchOne("select www_root from hosting where dom_id='".$row['id']."'");
            $form->addElement('checkbox', 'domainCheckbox'.$row['id'], array(
                'label' => $row['name'].": ".$domainRoot,
                'value' => pm_Settings::get('domainCheckbox'.$row['id']),
            ));
        }


        $form->addControlButtons(array(
            'cancelLink' => pm_Context::getModulesListUrl(),
        ));
        $scanlist = array();
        if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
            // Form proccessing here
            pm_Settings::set('emailText', $form->getValue('emailText'));
            pm_Settings::set('scheduleSelect', $form->getValue('scheduleSelect'));
            $domainset = pm_Bootstrap::getDbAdapter()->query("select * from domains where htype='vrt_hst'");
            pm_Settings::set('cronMinute', $form->getValue('cronMinute'));
            pm_Settings::set('cronHour', $form->getValue('cronHour'));
            pm_Settings::set('cronDOW', $form->getValue('cronDOW'));
            pm_Settings::set('cronDOM', $form->getValue('cronDOM'));
            pm_Settings::set('cronMonth', $form->getValue('cronMonth'));
            while ($row = $domainset->fetch()) {
                pm_Settings::set('domainCheckbox'.$row['id'], $form->getValue('domainCheckbox'.$row['id']));
                if (pm_Settings::get('domainCheckbox'.$row['id']) == 1)
                    $domainRoot = pm_Bootstrap::getDbAdapter()->fetchOne("select www_root from hosting where dom_id='".$row['id']."'");
                    array_push($scanlist, $domainRoot);
            }
            $this->_status->addMessage('info', 'Scan Settings were successfully saved.');
            if( $form->getValue('scheduleSelect') != 'opt-0'){

                if($form->getValue('emailText')){
                    pm_Bootstrap::init();
                    pm_Bootstrap::getDbAdapter()->query("INSERT INTO misc(param, val) VALUES( 'clamnotify', '".$form->getValue('emailText')."') ON DUPLICATE KEY UPDATE val='".$form->getValue('emailText')."'");
                }
                
				$task2 = new pm_Scheduler_Task();
				// Lets set	task to put logs in database 
                if (pm_Settings::get('clamav_freshclam_taskid2')) {
                    $taskId2 = pm_Settings::get('clamav_freshclam_taskid2');
                    $task2 = pm_Scheduler::getInstance()->getTaskById($taskId2);
                    pm_Scheduler::getInstance()->removeTask($task2);
                    }

				$task2->setSchedule(array(
                    'minute' => "*/3", 
                    'hour' => "*",
                    'dom' => "*",
                    'month' => "*",
                    'dow' => "*"
                    ));
                $task2->setCmd("clamscan_logcleaner.php"); 
				pm_Context::init('clamav');
                pm_Scheduler::getInstance()->putTask($task2);
                pm_Settings::set('clamav_freshclam_taskid2', $task2->getId());
				
				
				//Main Task
				$task = new pm_Scheduler_Task();
                if (pm_Settings::get('clamav_freshclam_taskid')) {
                    $taskId = pm_Settings::get('clamav_freshclam_taskid');
                    $task = pm_Scheduler::getInstance()->getTaskById($taskId);
                    pm_Scheduler::getInstance()->removeTask($task);
                    }

				
				// Back to setting up main scan task
                if ($form->getValue('scheduleSelect') == 'opt-1'){ $task->setSchedule(pm_Scheduler::$EVERY_HOUR);}
                if ($form->getValue('scheduleSelect') == 'opt-2'){ $task->setSchedule(pm_Scheduler::$EVERY_DAY);}
                if ($form->getValue('scheduleSelect') == 'opt-3'){ $task->setSchedule(pm_Scheduler::$EVERY_WEEK);}
                if ($form->getValue('scheduleSelect') == 'opt-4'){ $task->setSchedule(pm_Scheduler::$EVERY_MONTH);}
                if ($form->getValue('scheduleSelect') == 'opt-5'){ 
                    $task->setSchedule(array(
                    'minute' => $form->getValue('cronMinute') , 
                    'hour' => $form->getValue('cronHour') ,
                    'dom' => $form->getValue('cronDOM') ,
                    'month' => $form->getValue('cronMonth') ,
                    'dow' => $form->getValue('cronDOW') 
                    ));}
                

                $task->setCmd('clamscan.php'); 
				//pm_Context::init('clamav');
                pm_Scheduler::getInstance()->putTask($task);
                // Save task id in order to remove it if necessary
                pm_Settings::set('clamav_freshclam_taskid', $task->getId());
                $file = pm_Context::getVarDir().'scanlist.dat';
                $scanliststr = implode("\n", array_unique($scanlist));  
                $fh = fopen($file , "w"); 
                fwrite($fh, $scanliststr);  
                fclose($fh); 
            }
            elseif (pm_Settings::get('clamav_freshclam_taskid2')) {
                $taskId = pm_Settings::get('clamav_freshclam_taskid');
                $task = pm_Scheduler::getInstance()->getTaskById($taskId);
                pm_Scheduler::getInstance()->removeTask($task);
				pm_Settings::set('clamav_freshclam_taskid',null);
                $taskId2 = pm_Settings::get('clamav_freshclam_taskid2');
                $task2 = pm_Scheduler::getInstance()->getTaskById($taskId2);
                pm_Scheduler::getInstance()->removeTask($task2);
                pm_Settings::set('clamav_freshclam_taskid2',null);
            }

            $this->_helper->json(array('redirect' => pm_Context::getBaseUrl()));
        }


        $this->view->form = $form;
    }

    public function toolsAction()
    {
        // Tools for pm_View_Helper_RenderTools
        $this->view->tools = array(
            array(
                'icon' => $this->view->skinUrl('/') . "img/icons/big/site-aps_32.gif",
                'title' => 'Example',
                'description' => 'Example module with UI samples',
                'link' => pm_Context::getBaseUrl(),
            ),
            array(
                'icon' => $this->view->skinUrl('/') . "img/icons/big/modules_32.gif",
                'title' => 'Modules',
                'description' => 'Modules installed in the Panel',
                'link' => pm_Context::getModulesListUrl(),
            ),
        );

        // Tools for pm_View_Helper_RenderSmallTools
        $this->view->smallTools = array(
            array(
                'title' => 'Example',
                'description' => 'Example module with UI samples',
                'class' => 'sb-app-info',
                'link' => pm_Context::getBaseUrl(),
            ),
            array(
                'title' => 'Modules',
                'description' => 'Modules installed in the Panel',
                'class' => 'sb-suspend',
                'link' => pm_Context::getModulesListUrl(),
            ),
        );
    }

    public function listAction()
    {
 
		$rid =  $this->getRequest()->getParam('rid');
		$del =  $this->getRequest()->getParam('del');
		
		if ($rid != null) {
			pm_Bootstrap::init();
			$content = pm_Bootstrap::getDbAdapter()->query("select * from clamav_logs where id='".$rid."' ORDER BY date ASC");
			while ($row = $content->fetch()) {

			$length = strlen($row['results']);

			header('Content-Description: File Transfer');
			header('Content-Type: text/plain');//<<<<
			header('Content-Disposition: attachment; filename='.$row['id']);
			header('Content-Transfer-Encoding: binary');
			header('Content-Length: ' . $length);
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Expires: 0');
			header('Pragma: public');

			echo $row['results'];
			exit;
		
			}
		}
		if ($del != null) {
			pm_Bootstrap::init();
			pm_Bootstrap::getDbAdapter()->query("DELETE FROM clamav_logs where id='".$del."'");
			
		}
		
       $list = $this->_getListRandom();

        // List object for pm_View_Helper_RenderList
        $this->view->list = $list;

		
	}

    public function listDataAction()
    {
	
	  
        $list = $this->_getListRandom();

        // Json data from pm_View_List_Simple
        $this->_helper->json($list->fetchData());
    }

    private function _getListRandom()
    {
        pm_Bootstrap::init();
       // $directory = pm_Context::getHtdocsDir() . '';
       // $logfiles = glob($directory . "*.txt");
        //$iconPath = $this->view->skinUrl('/') . "img/icons/small/ok_16.gif"; //pm_Context::getBaseUrl() . 'images/icon_16.gif';
        $data = array();
		$logSet = pm_Bootstrap::getDbAdapter()->query("select * from  clamav_logs ORDER BY date(date), time(date) DESC");
		while ($row = $logSet->fetch()) {
			$iconPath = $this->view->skinUrl('/') . "img/icons/small/ok_16.gif";
            if($row['virus']) {
                $sresult = "Virus Found";   
				$iconPath = $this->view->skinUrl('/') . "img/icons/small/warning_16.gif";
            } 
            else {
                $sresult = "Clean";	
				
            }
            if($row['status']) {
                $status = "Scan Complete";   
            } 
            else {
                $status = "Running";	
            }
            
            $data[] = array(
                'column-1' => '<a href="?rid='.$row['id'].'">Scan - ' . $row['date'] . '</a>',
                'column-2' => '<img src="' . $iconPath . '" />  '. $sresult,
				'column-3' => $status ,
				'column-4' => '<a href="?del='.$row['id'].'"> Delete Report </a>',
                );
        }
        $list = new pm_View_List_Simple($this->view, $this->_request);
        $list->setData($data);
        $list->setColumns(array(
            'column-1' => array(
                'title' => 'Scan Results',
                'noEscape' => true,
            ),
            'column-2' => array(
                'title' => 'Virus Found?',
                'noEscape' => true,
            ),
           'column-3' => array(
                'title' => 'Scan Status',
                'noEscape' => true,
            ),
           'column-4' => array(
                'title' => 'Remove Report?',
                'noEscape' => true,
            ),
        ));
        // Take into account listDataAction corresponds to the URL /list-data/
        $list->setDataUrl(array('action' => 'list-data'));


        return $list;
    }
}
